//
//  OnlineOLDetailViewController.m
//  ShangHaiHuDongApp
//
//  Created by apple on 17/9/4.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "OnlineOLDetailViewController.h"

//头部cell
#import "OnlineOLTitleTableViewCell.h"
#define TITLECELL @"OnlineOLTitleTableViewCell"

//详情cell
#import "OnlineOLDetailTableViewCell.h"
#define DETAILCELL @"OnlineOLDetailTableViewCell"

//视频资源Cell
#import "OnlineVideoAssetTableViewCell.h"
#define VIDEOCELL @"OnlineVideoAssetTableViewCell"

//文件资源cell
#import "OnlineFileAssetTableViewCell.h"
#define FILECELL @"OnlineFileAssetTableViewCell"

//总结cell
#import "OnlineOLTotalTableViewCell.h"
#define TOTALCELL @"OnlineOLTotalTableViewCell"

#import "YBRequestManager.h"

#import "YTKKeyValueStore.h"
#import "LPWebWatchResouceViewController.h"
#import "LCustomAlertView.h"

#import "StudyCoureVideoViewController.h"
#import "ZJStudyRecommendModel.h"
//参与人数筛选
#import "LPJoinPersonListViewController.h"

//写总结页面
#import "YBProjectDetailSummarizeViewController.h"

//聊天室界面
#import "ZJDiscussViewController.h"

//暂无cell
#import "LPActivityDetailStudyNoDataTableViewCell.h"
#define NULLCELL @"LPActivityDetailStudyNoDataTableViewCell"

#define RESOUCESURFACE @"resouce.db"
#define RESOUCE_TABLE @"resouce_table"


@interface OnlineOLDetailViewController ()<UITableViewDelegate , UITableViewDataSource , OnlineOLTotalModelDelegate , LCustomAlertDelegate , OnlineOLTitleTableViewCellDelegate , NSURLConnectionDelegate,NSURLConnectionDataDelegate>
{
    NSURLConnection *_downConnection;
}
/**  是否是书记  */
@property (nonatomic , assign) BOOL isSecretary;
/**  是否已经写了总结  */
@property (nonatomic , assign) BOOL isWrite;
/**  是否已经结束  */
@property (nonatomic , assign) BOOL isEnd;

/**  第一次进入  */
@property (nonatomic , assign) BOOL isFirstIn;

@property (nonatomic , strong) UITableView * mainTableView;
/**  详情model  */
@property (nonatomic , strong) OnlineOLDetailModel * detailModel;

/**  总结model  */
@property (nonatomic , strong) OnlineOLTotalModel * totalModel;

/**  视频资源model数组  */
@property (nonatomic , strong) NSMutableArray<OnlineVideoAssetModel *> * videoAssetArray;

/**  视频资源进入下个界面model数组  */
@property (nonatomic , strong) NSMutableArray * videoEnterArray;

/**  文件资源数组  */
@property (nonatomic , strong) NSMutableArray<LPActDetailResouceModel *> * fileAssetArray;

/**  进入聊天室button  */
@property (nonatomic , strong) UIButton * enterChatGroupButton;

/**  修改／写总结button  */
@property (nonatomic , strong) UIButton * writeButton;

/**  结束button  */
@property (nonatomic , strong) UIButton * endButton;

/**  选中的model  */
@property (strong, nonatomic) LPActDetailResouceModel  *chooseModel;

/**  jc  */
@property (strong, nonatomic) JCAlertView  *jcAlertView;

@property (nonatomic , strong) UIView * nullView;
/**  判断是否报名  */
@property (strong, nonatomic) NSString  *ENROLL_COUNT;
/**  判断是否签到  */
@property (strong, nonatomic) NSString  *SIGN_COUNT;

@end

@implementation OnlineOLDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (ZJUSERINFORMODEL.isSecretary) {
        self.isSecretary = YES;
    }
    else{
        self.isSecretary = NO;
    }
    self.isWrite = NO;
    self.isEnd = NO;
    self.isFirstIn = YES;
    if (self.model.NAME.length > 0) {
        [self setAnimationTitle];
    }
    [self ybInitInterface];
    [self ybInitDataSource];
}
- (void)action_leftButton:(UIButton *)sender{
    if (self.isModel) {
        [LPCostomPressentAnimationSimilarityPushAnimation backLastVc];
        [self.navigationController dismissViewControllerAnimated:NO completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.isFirstIn) {
        [self ybRefreshData];
    }
    else{
        self.isFirstIn = NO;
    }
}


-(void)setAnimationTitle{
    NSString * myTitleString = [NSString stringWithFormat:@"%@" , self.model.NAME];
    CGFloat titleWidth = [myTitleString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : LYPFONT(17)} context:nil].size.width;
    if (titleWidth < ([UIScreen zj_screenWith] - 108)) {
        self.titlelabel.text = myTitleString;
    }
    else{
        UIView * titleContentView = [[UIView alloc]initWithFrame:CGRectMake(54, 20, [UIScreen zj_screenWith] - 108, 44)];
        titleContentView.backgroundColor = [UIColor themeColor];
        titleContentView.clipsToBounds = YES;
        [self.navigView addSubview:titleContentView];
        UILabel * animationTitleLabel = [ToolClass creatLabelWithFrame:CGRectMake([UIScreen zj_screenWith] - 108, 0, titleWidth + [UIScreen zj_screenWith] - 108, 44) font:17 textColor:[UIColor whiteColor] text:myTitleString];
        animationTitleLabel.layer.anchorPoint = CGPointMake(0, 0.5);
        [titleContentView addSubview:animationTitleLabel];
        CABasicAnimation * basicAnimation = [CABasicAnimation animation];
        basicAnimation.keyPath = @"position.x";
        basicAnimation.fromValue = @([UIScreen zj_screenWith] - 108);
        basicAnimation.toValue = @(-titleWidth);
        basicAnimation.duration = titleWidth / ([UIScreen zj_screenWith] - 108) * 8;
        basicAnimation.repeatCount = INT_MAX;
        basicAnimation.beginTime = CACurrentMediaTime();
        [animationTitleLabel.layer addAnimation:basicAnimation forKey:@"basicAnimation"];
    }
}



-(void)ybInitInterface{
    [self.view addSubview:self.mainTableView];
    UIView * bottomContentView = [[UIView alloc]initWithFrame:CGRectMake(0, [UIScreen zj_screenHeight] - ItemHeight * 88, [UIScreen zj_screenWith], ItemHeight * 88)];
    bottomContentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomContentView];
    [bottomContentView addSubview:self.enterChatGroupButton];
    [bottomContentView addSubview:self.writeButton];
    [bottomContentView addSubview:self.endButton];
    [self reloadBottomContentView];
    [self initDeleteView];
}

-(void)ybInitDataSource{
    
    [YJProgressHUD showMessage:@"加载中..." duration:10 view:self.view];
    [YBRequestManager request_OnlineOLDetailInfoWithActivityId:self.model.ID successBlock:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            self.model = [OnlineOrganizationalLifeModel yy_modelWithJSON:object[@"INFO"]];
            self.ENROLL_COUNT = [object objectForKey:@"ENROLL_COUNT"];
            self.SIGN_COUNT = [object objectForKey:@"SIGN_COUNT"];
            self.totalModel = [OnlineOLTotalModel yy_modelWithJSON:object[@"INFO"]];
            self.model.DELETED = self.totalModel.DELETED;
            [self isHiddenDeleteView];
            if ([self.model.DELETED integerValue] != -1) {
                self.detailModel = [OnlineOLDetailModel yy_modelWithJSON:object[@"INFO"]];
                NSArray * cTempArray = object[@"INFO"][@"COVER_JSON"];
                if (cTempArray.count > 0) {
                    self.detailModel.imageUrlString = [NSString stringWithFormat:@"%@" , object[@"INFO"][@"COVER_JSON"][0][@"file_path"]];
                }
                else{
                    self.detailModel.imageUrlString = @"";
                }
                [self.detailModel ybCalculateCellSubViewSize];
                if (self.model.NAME.length == 0) {
                    self.model.NAME = self.detailModel.titleString;
                    [self setAnimationTitle];
                }
                
                [self.totalModel calculateCellContentSize];
                self.model.SUMMARY = self.totalModel.contentString;
                self.totalModel.isOpen = NO;
                
                self.videoAssetArray = [[NSArray yy_modelArrayWithClass:[OnlineVideoAssetModel class] json:object[@"STUDY_LIST"]] mutableCopy];
                
                self.videoEnterArray = [[NSArray yy_modelArrayWithClass:[ZJStudyRecommendModel class] json:object[@"STUDY_LIST"]] mutableCopy];
                
                for (OnlineVideoAssetModel * videoModel in self.videoAssetArray) {
                    [videoModel calculateCellTitleSize];
                }
                
                self.fileAssetArray = [[NSArray yy_modelArrayWithClass:[LPActDetailResouceModel class] json:object[@"MAT_LIST"]] mutableCopy];
                
                self.model.IS_END = self.totalModel.IS_END;
                if ([self.totalModel.IS_END integerValue] == 3) {
                    self.isEnd = YES;
                }
                else{
                    self.isEnd = NO;
                }
                if (self.totalModel.SUMMARY_LASTTIME.length > 0) {
                    self.isWrite = YES;
                }
                else{
                    self.isWrite = NO;
                }
                [self reloadBottomContentView];
                [self.mainTableView reloadData];
                [YJProgressHUD hide];
            }
            else{
                if (self.block) {
                    self.block();
                }
            }
        }
        else{
            [YJProgressHUD hide];
            [LYEmptyManager showLoadFailWithView:self.mainTableView managerBlock:^{
                [self ybInitDataSource];
            }];
        }
    } failBlock:^(id object) {
        [YJProgressHUD hide];
        [YJProgressHUD showMsgWithoutView:@"请求失败"];
        [LYEmptyManager showLoadFailWithView:self.mainTableView managerBlock:^{
            [self ybInitDataSource];
        }];
    }];
}


-(void)initDeleteView{
    self.nullView = [[UIView alloc]initWithFrame:CGRectMake(0, LP_TopHeight, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] -  LP_TopHeight)];
    self.nullView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.nullView];
    //删除活动图片
    UIImageView * nullImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ItemWidth * 237, ItemHeight * 376)];
    nullImageView.image = [UIImage imageNamed:@"img_activity_cancel"];
    nullImageView.center = CGPointMake([UIScreen zj_screenWith] / 2, ([UIScreen zj_screenHeight] -  LP_TopHeight) / 2);
    [self.nullView addSubview:nullImageView];
    [self isHiddenDeleteView];
}

-(void)isHiddenDeleteView{
    if ([self.model.DELETED integerValue] == -1) {
        self.nullView.hidden = NO;
    }
    else{
        self.nullView.hidden = YES;
    }
}


-(void)ybRefreshData{
    [YBRequestManager request_OnlineOLDetailInfoWithActivityId:self.model.ID successBlock:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            self.model = [OnlineOrganizationalLifeModel yy_modelWithJSON:object[@"INFO"]];
            self.ENROLL_COUNT = [object objectForKey:@"ENROLL_COUNT"];
            self.SIGN_COUNT = [object objectForKey:@"SIGN_COUNT"];
            self.totalModel = [OnlineOLTotalModel yy_modelWithJSON:object[@"INFO"]];
            self.model.DELETED = self.totalModel.DELETED;
            [self isHiddenDeleteView];
            if ([self.model.DELETED integerValue] != -1) {
                [self.totalModel calculateCellContentSize];
                self.model.SUMMARY = self.totalModel.contentString;
                
                
                self.detailModel = [OnlineOLDetailModel yy_modelWithJSON:object[@"INFO"]];
                
                NSArray * cTempArray = object[@"INFO"][@"COVER_JSON"];
                if (cTempArray.count > 0) {
                    self.detailModel.imageUrlString = [NSString stringWithFormat:@"%@" , object[@"INFO"][@"COVER_JSON"][0][@"file_path"]];
                }
                else{
                    self.detailModel.imageUrlString = @"";
                }
                [self.detailModel ybCalculateCellSubViewSize];
                
                self.videoAssetArray = [[NSArray yy_modelArrayWithClass:[OnlineVideoAssetModel class] json:object[@"STUDY_LIST"]] mutableCopy];
                
                self.videoEnterArray = [[NSArray yy_modelArrayWithClass:[ZJStudyRecommendModel class] json:object[@"STUDY_LIST"]] mutableCopy];
                
                for (OnlineVideoAssetModel * videoModel in self.videoAssetArray) {
                    [videoModel calculateCellTitleSize];
                }
                
                self.fileAssetArray = [[NSArray yy_modelArrayWithClass:[LPActDetailResouceModel class] json:object[@"MAT_LIST"]] mutableCopy];
                
                self.model.IS_END = self.totalModel.IS_END;
                if ([self.totalModel.IS_END integerValue] == 3) {
                    self.isEnd = YES;
                }
                else{
                    self.isEnd = NO;
                }
                if (self.totalModel.SUMMARY_LASTTIME.length > 0) {
                    self.isWrite = YES;
                }
                else{
                    self.isWrite = NO;
                }
                [self reloadBottomContentView];
                [self.mainTableView reloadData];
            }
            else{
                if (self.block) {
                    self.block();
                }
            }
        }
    } failBlock:^(id object) {
        
    }];
}



-(void)reloadBottomContentView{
    if (self.isSecretary) {
        if (!self.isEnd) {
            if (!self.isWrite) {
                self.enterChatGroupButton.frame = CGRectMake(0, 0, [UIScreen zj_screenWith] - 220 * ItemWidth, ItemHeight * 88);
                self.writeButton.hidden = NO;
                [self changeModifyButtonTitleWithString:@"写总结"];
                self.endButton.hidden = NO;
            }
            else{
                self.enterChatGroupButton.frame = CGRectMake(0, 0, [UIScreen zj_screenWith] - 220 * ItemWidth, ItemHeight * 88);
                self.writeButton.hidden = NO;
                [self changeModifyButtonTitleWithString:@"修改总结"];
                self.endButton.hidden = NO;
            }
        }
        else{
            self.enterChatGroupButton.frame = CGRectMake(0, 0, [UIScreen zj_screenWith], ItemHeight * 88);
            self.writeButton.hidden = YES;
            self.endButton.hidden = YES;
        }
    }
    else{
        self.enterChatGroupButton.frame = CGRectMake(0, 0, [UIScreen zj_screenWith], ItemHeight * 88);
        self.writeButton.hidden = YES;
        self.endButton.hidden = YES;
    }
    NSString * chatGroupNumberString = @"0";
    if (self.detailModel.ENROLL_NUM.length > 0) {
        chatGroupNumberString = self.detailModel.ENROLL_NUM;
    }
    [self.enterChatGroupButton setTitle:[NSString stringWithFormat:@"进入讨论室（%@）" , chatGroupNumberString] forState:UIControlStateNormal];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return ItemHeight * 391;
    }
    else if (indexPath.section == 1){
        return self.detailModel.totalHeight;
    }
    else if (indexPath.section == 2){
        if (self.fileAssetArray.count > 0 || self.videoAssetArray.count > 0) {
            if (indexPath.row < self.videoAssetArray.count) {
                return ItemHeight * 220;
            }
            else{
                return ItemHeight * 88;
            }
        }
        else{
            return 80 * [UIScreen zj_screenHScale];
        }
    }
    else{
        if (self.totalModel.isMoreThanFiveLine) {
            if (self.totalModel.isOpen) {
                return self.totalModel.onContentSize.height + ItemHeight * 126;
            }
            else{
                return self.totalModel.offContentSize.height + ItemHeight * 126;
            }
        }
        else{
            return self.totalModel.onContentSize.height + ItemHeight * 126;
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return 0.01;
    }
    else{
        return ItemHeight * 65;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.isSecretary) {
        if (self.isWrite) {
            return 4;
        }
        else{
            return 3;
        }
    }
    else{
        return 3;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 1 || section == 3) {
        return 1;
    }
    else{
        if (self.fileAssetArray.count > 0 || self.videoAssetArray.count > 0) {
            return self.videoAssetArray.count + self.fileAssetArray.count;
        }
        else{
            return 1;
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        OnlineOLTitleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:TITLECELL forIndexPath:indexPath];
        cell.delegate = self;
        [cell.titleImageView sd_setImageWithURL:CREATEURL(self.detailModel.imageUrlString) placeholderImage:PlaceholderHUODONGBIGImage];
        NSString * joinNumberString = @"0";
        if (self.detailModel.ENROLL_NUM.length > 0) {
            joinNumberString = self.detailModel.ENROLL_NUM;
        }
        NSString * joinString = [NSString stringWithFormat:@"参与人数：%@" , joinNumberString];
        NSMutableAttributedString * joinAttributedString = [[NSMutableAttributedString alloc]initWithString:joinString];
        [joinAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor zj_colorWithHexString:@"f24141"] range:NSMakeRange(5, joinString.length - 5)];
        cell.joinPeopleNumberLabel.attributedText = joinAttributedString;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section == 1){
        OnlineOLDetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:DETAILCELL forIndexPath:indexPath];
        if (self.detailModel.titleString.length > 0 || self.detailModel.contentString.length > 0) {
            cell.model = self.detailModel;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section == 2){
        if (self.fileAssetArray.count > 0 || self.videoAssetArray.count > 0) {
        if (indexPath.row < self.videoAssetArray.count) {
            OnlineVideoAssetTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:VIDEOCELL forIndexPath:indexPath];
            cell.model = self.videoAssetArray[indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        else{
            OnlineFileAssetTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:FILECELL forIndexPath:indexPath];
            cell.model = self.fileAssetArray[indexPath.row - self.videoAssetArray.count];
            if (indexPath.row == (self.videoAssetArray.count + self.fileAssetArray.count - 1)) {
                cell.bottomView.hidden = YES;
            }
            else{
                cell.bottomView.hidden = NO;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
        else{
            LPActivityDetailStudyNoDataTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NULLCELL forIndexPath:indexPath];
            cell.title.text = @"暂无资源";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
    else{
        OnlineOLTotalTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:TOTALCELL forIndexPath:indexPath];
        cell.delegate = self;
        if (self.totalModel.contentString.length > 0) {
            cell.model = self.totalModel;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[NSString stringWithFormat:@"header%ld" , section]];
    if (!header) {
        header = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:[NSString stringWithFormat:@"header%ld" , section]];
        if (section == 2 || section == 3) {
            UILabel * theTitleLabel = [ToolClass creatLabelWithFrame:CGRectMake(ItemWidth * 22, 0, [UIScreen zj_screenWith] * 0.75, ItemHeight * 65) font:16 textColor:[UIColor textGrayColor] text:@""];
            if (section == 2) {
                theTitleLabel.text = @"相关资源";
            }
            else{
                theTitleLabel.text = @"总结";
            }
            [header.contentView addSubview:theTitleLabel];
        }
    }
    return header;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        if (indexPath.row < self.videoAssetArray.count) {
            StudyCoureVideoViewController *vc = [StudyCoureVideoViewController new];
            vc.model = self.videoEnterArray[indexPath.row];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else{
            LPActDetailResouceModel *model = self.fileAssetArray[indexPath.row - self.videoAssetArray.count];
            self.chooseModel = model;
            /**  获取本地文件路径  */
            NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
            /**  创建表  */
            YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:@"resouce.db"];
            [store createTableWithName:@"resouce_table"];
            
            /**  获取文件后缀  */
            NSArray *stringArray = [NSString getArrayFromString:model.FILE_PATH byString:@"."];
            //获取保存数据
            NSArray *downArray = [store getObjectById:ZJUSERINFORMODEL.ORG_ACCOUNT.ID fromTable:@"resouce_table"];
            /**  创建目录  */
            NSString *testDirectory = [documentsDirectory stringByAppendingString:@"/downResoucee"];
            /**  通过ID得到唯一标识  */
            NSString *testString = [NSString stringWithFormat:@"/%@.%@",model.ID,stringArray.lastObject];
            //  创建文件
            NSString *testPath = [testDirectory stringByAppendingPathComponent:testString];
            NSInteger flog = 0;
            NSDictionary *resouceDic;
            for (NSDictionary *dic  in downArray) {
                if ([dic[@"resouce"] isEqualToString:testString]) {
                    flog = 1;
                    resouceDic = dic;
                }
            }
            
            if (flog == 1) {
                /**  从本地判断，存在直接观看  */
                LPWebWatchResouceViewController *vc = [LPWebWatchResouceViewController new];
                vc.headLine = model.NAME;
                vc.urlString = testPath;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                /**  不存在就弹出下载  */
                [self downAlertView];
                
            }
        }
    }
}

- (void)downAlertView{
    LCustomAlertView *alert = [[LCustomAlertView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) alertMessage:@"下载才能查看,是否下载" titlesArray:@[@"取消", @"确认"]];
    alert.tag = 1;
    alert.delegate = self;
    self.jcAlertView = [[JCAlertView alloc] initWithCustomView:alert dismissWhenTouchedBackground:YES];
    [self.jcAlertView show];
    
}



#pragma mark - LCustomAlertDelegate
- (void)lCustomAlertWithView:(LCustomAlertView *)view index:(NSInteger)index{
    if (view.tag == 1) {
        /**  这是下载的弹窗  */
        if (index == 1) {
            [YJProgressHUD show:@"下载中..." inView:self.view mode:YJProgressModeLoading];
            /**  创建表  */
            YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:@"resouce.db"];
            [store createTableWithName:RESOUCE_TABLE];
            //获取保存数据
            NSArray *downArray = [store getObjectById:ZJUSERINFORMODEL.ORG_ACCOUNT.ID fromTable:RESOUCE_TABLE];
            
            
            /**  获取本地文件路径  */
            NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
            /**  获取文件后缀  */
            NSArray *stringArray = [NSString getArrayFromString:self.chooseModel.FILE_PATH byString:@"."];
            /**  创建目录  */
            NSString *testDirectory = [documentsDirectory stringByAppendingString:@"/downResoucee"];
            /**  通过ID得到唯一标识  */
            NSString *testString = [NSString stringWithFormat:@"/%@.%@",self.chooseModel.ID,stringArray.lastObject];
            //  创建文件
            NSString *testPath = [testDirectory stringByAppendingPathComponent:testString];
            
            NSString *urlstring = [NSString stringWithFormat:@"%@/%@",DOWNFILE,self.chooseModel.FILE_PATH];
            urlstring = [urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:urlstring];
            //创建请求
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            
            //方法二：发送一个异步请求
            [NSURLConnection sendAsynchronousRequest:request
                                               queue:[NSOperationQueue mainQueue]
                                   completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                       [YJProgressHUD hide];
                                       if (!connectionError) {
                                           
                                           NSData *doubi = data;
                                           NSMutableArray *allArray = [NSMutableArray array];
                                           [allArray addObjectsFromArray:downArray];
                                           //  二进制流写入文件
                                           NSFileManager *fileManger = [NSFileManager defaultManager];
                                           //  创建目录
                                           [fileManger createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
                                           
                                           //  写入文件
                                           [fileManger createFileAtPath:testPath contents:doubi attributes:nil];
                                           
                                           /**  整合数据  */
                                           NSDictionary *dataDic = @{@"resouce": testString};
                                           [allArray addObject:dataDic];
                                           
                                           [store putObject:allArray withId:ZJUSERINFORMODEL.ORG_ACCOUNT.ID intoTable:RESOUCE_TABLE];
                                           
                                           LPWebWatchResouceViewController *vc = [LPWebWatchResouceViewController new];
                                           vc.headLine = self.chooseModel.NAME;
                                           vc.urlString = testPath;
                                           [self.navigationController pushViewController:vc animated:YES];
                                           
                                           
                                           
                                       } else {
                                           [YJProgressHUD showMsgWithoutView:@"下载失败"];
                                           
                                       }
                                   }];
            
        }
    }else if (view.tag == 2){
        /**  这是报名弹窗  */
        if (index == 1) {
            __weak typeof(self) weakSelf = self;
            [YJProgressHUD show:@"报名中..." inView:self.view mode:YJProgressModeLoading];
            /**  这是点击加入  */
            NSDictionary *paramer = @{@"AI_ID": self.model.ID,
                                      @"USER_ID": ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID,
                                      @"USER_NAME": ZJUSERINFORMODEL.ORG_ACCOUNT.USER_NAME};
            [NetWorkingManager postWithUrlString:[NetWorkingURL getactactionMobileEnroll] Parameter:paramer Success:^(id object) {
                NSString *CODE = [object objectForKey:@"CODE"];
                if ([CODE isEqualToString:@"20000"]) {
                    if (weakSelf.applyBlock) {
                        weakSelf.applyBlock();
                    }
                    [MobClick event:[UMMStatisticsString registerAct]];
                    [YJProgressHUD showMsgWithoutView:@"报名成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        ZJDiscussViewController * discussVC = [[ZJDiscussViewController alloc]init];
                        discussVC.model = weakSelf.model;
                         discussVC.sign_count = weakSelf.SIGN_COUNT;
                        [weakSelf.navigationController pushViewController:discussVC animated:YES];
                    });
                   
                    
                }else if ([CODE isEqualToString:@"80001"]) {
                    [YJProgressHUD showMsgWithoutView:@"重复报名"];
                }else if ([CODE isEqualToString:@"80002"]) {
                    [YJProgressHUD showMsgWithoutView:@"活动结束"];
                }else if ([CODE isEqualToString:@"80003"]) {
                    [YJProgressHUD showMsgWithoutView:@"人数达上限"];
                }else if ([CODE isEqualToString:@"80004"]) {
                    [YJProgressHUD showMsgWithoutView:@"无此活动或已被删除!"];
                }else{
                    [YJProgressHUD showMsgWithoutView:@"报名失败"];
                }
                
            } Fail:^(id object) {
                [YJProgressHUD showMsgWithoutView:@"报名失败"];
            }];
        }
    }
    
    [self.jcAlertView dismissWithCompletion:nil];
}
//点击全文-收起方法
-(void)didClickOpenButtonWithBottonOpenState:(BOOL)state
{
    self.totalModel.isOpen = state;
    [self.mainTableView reloadData];
}

//修改写总结button title方法
-(void)changeModifyButtonTitleWithString:(NSString *)string{
    UILabel * textLabel = (UILabel *)([self.writeButton viewWithTag:110]);
    if (textLabel) {
        textLabel.text = string;
    }
}


#pragma mark 进入聊天室按钮
-(void)option_enterChatRoomButton:(UIButton *)sender{
    
    if ([self.model.IS_END integerValue] == 3) {
        /**  活动已结束，已报名才可以进入讨论室  */
        if ([self.ENROLL_COUNT integerValue] == 1) {
            ZJDiscussViewController * discussVC = [[ZJDiscussViewController alloc]init];
            discussVC.model = self.model;
            discussVC.sign_count = self.SIGN_COUNT;
            [self.navigationController pushViewController:discussVC animated:YES];
        }else{
            [YJProgressHUD showMessage:@"活动已结束" inView:self.view afterDelayTime:1];
        }
    }else{
        /**  活动未结束，已报名才可以进入讨论室  */
        if ([self.ENROLL_COUNT integerValue] == 1) {
            ZJDiscussViewController * discussVC = [[ZJDiscussViewController alloc]init];
            discussVC.model = self.model;
             discussVC.sign_count = self.SIGN_COUNT;
            [self.navigationController pushViewController:discussVC animated:YES];
        }else{
            LCustomAlertView *alert = [[LCustomAlertView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) alertMessage:@"是否报名" titlesArray:@[@"取消", @"确认"]];
            alert.tag = 2;
            alert.delegate = self;
            self.jcAlertView = [[JCAlertView alloc] initWithCustomView:alert dismissWhenTouchedBackground:YES];
            [self.jcAlertView show];
        }

    
    }
    
}

#pragma mark 写总结按钮
-(void)option_writeButton:(UIButton *)sender{
    YBProjectDetailSummarizeViewController * summarizeVC = [[YBProjectDetailSummarizeViewController alloc]init];
    summarizeVC.model = self.model;
    [self.navigationController pushViewController:summarizeVC animated:YES];
}


#pragma mark 结束按钮
-(void)option_endButton:(UIButton *)sender{
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否结束" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self endProject];
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}


/**  项目结束  */
- (void)endProject{
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD show:@"" inView:self.view mode:YJProgressModeLoading];
    NSDictionary *dict = @{@"AI_ID":self.model.ID,@"STATUS": @"2"};
    [NetWorkingManager postWithUrlString:[NetWorkingURL getactmactionActChangeStatusstatus] Parameter:dict Success:^(id object) {
        [YJProgressHUD hide];
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:weakSelf.model.ID];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ENDLIFEACT" object:nil];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }else{
             [YJProgressHUD showSuccess:@"网络错误" inview:weakSelf.view];
        }
    } Fail:^(id object) {
        [YJProgressHUD showSuccess:@"网络错误" inview:weakSelf.view];
        [YJProgressHUD hide];
    }];
    
    
}


#pragma mark 参加人数按钮
-(void)clickJoinPeopleNumberButton{
    /**  先判断是否是书记,再判断在册用户的UNITID和活动的UNITID是否一致  */
    if (ZJUSERINFORMODEL.isSecretary == NO || !ZJUSERINFORMODEL.DEPT_MODEL_BOOK || ![self.model.UNITID isEqualToString:ZJUSERINFORMODEL.DEPT_MODEL_BOOK.ID]) {
        return;
    }
    LPJoinPersonListViewController *vc = [LPJoinPersonListViewController new];
    ActivityJoinDetailModel * model = [[ActivityJoinDetailModel alloc]init];
    model.ID = self.model.ID;
    model.NAME = self.model.NAME;
    model.START_TIME = self.model.START_TIME;
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

-(UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, LP_TopHeight, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] - LP_TopHeight - ItemHeight * 88) style:UITableViewStyleGrouped];
        [_mainTableView registerClass:[OnlineOLTitleTableViewCell class] forCellReuseIdentifier:TITLECELL];
        [_mainTableView registerClass:[OnlineOLDetailTableViewCell class] forCellReuseIdentifier:DETAILCELL];
        [_mainTableView registerClass:[OnlineVideoAssetTableViewCell class] forCellReuseIdentifier:VIDEOCELL];
        [_mainTableView registerClass:[OnlineFileAssetTableViewCell class] forCellReuseIdentifier:FILECELL];
        [_mainTableView registerClass:[OnlineOLTotalTableViewCell class] forCellReuseIdentifier:TOTALCELL];
        [_mainTableView registerClass:[LPActivityDetailStudyNoDataTableViewCell class] forCellReuseIdentifier:NULLCELL];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.backgroundColor = [UIColor themeGrayColor];
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _mainTableView;
}

-(OnlineOLDetailModel *)detailModel
{
    if (!_detailModel) {
        _detailModel = [[OnlineOLDetailModel alloc]init];
    }
    return _detailModel;
}

-(OnlineOLTotalModel *)totalModel
{
    if (!_totalModel) {
        _totalModel = [[OnlineOLTotalModel alloc]init];
    }
    return _totalModel;
}

-(NSMutableArray<OnlineVideoAssetModel *> *)videoAssetArray
{
    if (!_videoAssetArray) {
        _videoAssetArray = [NSMutableArray array];
    }
    return _videoAssetArray;
}

-(NSMutableArray *)fileAssetArray
{
    if (!_fileAssetArray) {
        _fileAssetArray = [NSMutableArray array];
    }
    return _fileAssetArray;
}


-(UIButton *)enterChatGroupButton
{
    if (!_enterChatGroupButton) {
        _enterChatGroupButton = [ToolClass createButtonWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], ItemHeight * 88) text:@"" textColor:[UIColor whiteColor] imageName:@"" font:16];
        _enterChatGroupButton.backgroundColor = [UIColor themeColor];
        [_enterChatGroupButton addTarget:self action:@selector(option_enterChatRoomButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _enterChatGroupButton;
}

-(UIButton *)writeButton
{
    if (!_writeButton) {
        _writeButton = [ToolClass createUpDownButtonWithFrame:CGRectMake([UIScreen zj_screenWith] - 220 * ItemWidth, 0, 111 * ItemWidth, ItemHeight * 88) text:@"修改总结" textColor:[UIColor textBlackColor] imageName:@"discuss_xiezongjie" font:11 imageSize:ItemWidth * 40 theInterval:ItemWidth * 4];
        _writeButton.layer.borderColor = [UIColor themeColor].CGColor;
        _writeButton.layer.borderWidth = 0.5;
        [_writeButton addTarget:self action:@selector(option_writeButton:) forControlEvents:UIControlEventTouchUpInside];
        _writeButton.hidden = YES;
    }
    return _writeButton;
}

-(UIButton *)endButton
{
    if (!_endButton) {
        _endButton = [ToolClass createUpDownButtonWithFrame:CGRectMake([UIScreen zj_screenWith] - 110 * ItemWidth, 0, 110 * ItemWidth, ItemHeight * 88) text:@"结束" textColor:[UIColor textBlackColor] imageName:@"discuss_enddiscuss" font:11 imageSize:ItemWidth * 40 theInterval:ItemWidth * 4];
        _endButton.layer.borderColor = [UIColor themeColor].CGColor;
        _endButton.layer.borderWidth = 0.5;
        [_endButton addTarget:self action:@selector(option_endButton:) forControlEvents:UIControlEventTouchUpInside];
        _endButton.hidden = YES;
    }
    return _endButton;
}


-(NSMutableArray<ZJStudyRecommendModel *> *)videoEnterArray
{
    if (!_videoEnterArray) {
        _videoEnterArray = [NSMutableArray array];
    }
    return _videoEnterArray;
}

@end
